<template>
<div class="container">
<van-nav-bar
  title="黑马头条-登录"
/>
<div>
  <van-form @submit="onSubmit">
  <van-field
    v-model="user.mobile"
    required
    name="mobile"
    label="手机号"
    placeholder="请输入11位手机号"
    :rules="[{ required: true, message: '请填写正确的手机号',pattern: /^1[3-9]\d{9}$/ }]"
  />
  <van-field
    v-model="user.code"
    required
    type="password"
    name="code"
    label="密码"
    placeholder="请输入密码"
    :rules="[{ required: true, message: '请填写正确的密码',pattern: /^\d{6}$/}]"
  />
  <div style="margin: 16px;">
    <van-button round block type="info" native-type="submit" :disabled="isLoading" :loading="isLoading" loading-text="正在登陆中..." >登录</van-button>
  </div>
</van-form>
</div>
</div>

</template>
<script>
import { setToken } from '@/utils/token'
import { loginAPI } from '@/api'
import Notify from '@/ui/Notify'
import { setStorage } from '@/utils/storage.js'
export default {
  name: 'MyLogin',
  data () {
    return {
      user: {
        mobile: '13888888888', // 手机号
        code: '246810'// 验证码（密码必须是246810）
      },
      isLoading: false // 登录按钮的加载状态
    }
  },
  methods: {
    async onSubmit (values) {
      console.log('submit', values)

      // 状态设置为true
      this.isLoading = true

      try {
        const res = await loginAPI(this.user)
        // console.log(res)
        Notify({ type: 'success', message: '登陆成功！' })
        setToken(res.data.data.token)
        setStorage('refresh_token', res.data.data.refresh_token)
        // 跳转一定要写到最后
        this.$router.replace({
          path: this.$route.query.patj || '/layout/home'
        })
      } catch (err) {
        Notify({ type: 'danger', message: '账号或密码错误！' })
      }

      this.isLoading = false // 网络请求完成，无论成功/报错
    }
  }
}
</script>
<style scoped lang="less">
.van-nav-bar{
  background-color: #007bff;
}
/deep/ .van-nav-bar__title{
  color:white
}
</style>
